package com.example.skinmanager.Manager;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;

import androidx.core.content.ContextCompat;

import java.lang.reflect.Method;

public class SkinManager {
    private static SkinManager mInstance = new SkinManager();
    private Context context;
    private Resources resources;
    private String skinPackageName;

    private SkinManager() {

    }

    public static SkinManager getInstance() {
        return mInstance;
    }
    public void init(Context context){
        this.context = context;
    }
    public void loadSkin(String path)  {

        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageArchiveInfo(path,PackageManager.GET_ACTIVITIES);
            skinPackageName = packageInfo.packageName;
            //AssetManager构造方法被隐藏不能直接new
            AssetManager assetManager = AssetManager.class.newInstance();
            Method addAssetPathMethod = assetManager.getClass().getDeclaredMethod("addAssetPath",String.class);
            addAssetPathMethod.setAccessible(true);
            addAssetPathMethod.invoke(assetManager,path);
            //其余两个参数为配置类参数，直接拿原有的就行
            resources = new Resources(assetManager,context.getResources().getDisplayMetrics(),
                    context.getResources().getConfiguration());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public int getColor(int resId){
        if (resourceIsNull()){
            return resId;
        }
        String resourceTypeName = context.getResources().getResourceTypeName(resId);
        String resourceEntryName = context.getResources().getResourceEntryName(resId);
        int identifier = resources.getIdentifier(resourceEntryName, resourceTypeName, skinPackageName);
        if (identifier == 0){
            return resId;
        }
        return resources.getColor(identifier);
    }
    public Drawable getDrawable(int resId){
        if (resourceIsNull()){
            return ContextCompat.getDrawable(context,resId);
        }
        String resourceTypeName = context.getResources().getResourceTypeName(resId);
        String resourceEntryName = context.getResources().getResourceEntryName(resId);
        int identifier = resources.getIdentifier(resourceEntryName, resourceTypeName, skinPackageName);
        if (identifier == 0){
            return ContextCompat.getDrawable(context,resId);
        }
        return resources.getDrawable(identifier);
    }
    public boolean resourceIsNull(){
        if (resources == null){
            return true;
        }
        return  false;
    }
}
